import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {getAccountPermission} from '@/api/user'
import {asyncRouters} from '@/router/index'
import{creatrouter ,permission} from '@/utils/index'
// 进度条
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // 无重定向白名单
// 前守卫
router.beforeEach(async(to, from, next) => {

  // 进度条开始
  NProgress.start()

  // 设置网页标题
  document.title = getPageTitle(to.meta.title)

  // 判断用户是否登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      let accountId = JSON.parse(localStorage.getItem('adminAccountVO')) 
      let data={
        accountId:accountId.accountId
      }
     let result = await getAccountPermission(data)
      var arr = creatrouter(result.data , asyncRouters)
 
      var add=''
      arr.forEach((item=>{
        if(item.children){
          item.children.forEach(i=>{
            if(i.children){
              i.children.forEach(e=>{
                add = `${item.path}/${i.path}/${e.path}`
              })
            }
          })
        }
       }));
       localStorage.setItem("add", add);
            next({ path: add})
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      //  判断有没有 角色表
      if(!store.getters.roles ){
        let accountId = JSON.parse(localStorage.getItem('adminAccountVO')) 
        let data={
          accountId:accountId.accountId
        }
   
       let result = await getAccountPermission(data)
       store.commit('user/SET_ROLES',accountId)
      result.data.forEach(v => {
          if( ['统计','设置','权限'].includes( v.menuName)){
              v.permissionList = [ {  menuName:v.menuName, menuPath:v.menuPath.substring(1),menType:1 ,permissionList:v.permissionList  ,hasFlag:v.hasFlag } ]
          }
      });
     
       var arr = creatrouter(result.data , asyncRouters)
       store.commit('user/SET_ROUTES2',arr)
       store.commit('user/SET_permission',   permission(result.data))
       router.addRoutes(arr)
       next({  ...to , replace:true })
      }
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          next()
        } catch (error) {
          // 删除令牌，转到登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
         
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 么有token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免费登录白名单中，直接跳转
      next()
    } else {
      // 其他没有访问权限的页面将被重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
// 后守卫
router.afterEach(() => {
  // 进度条结束
  NProgress.done()
})